bl_info = {
    "name": "Model Manager",
    'author': '会飞的键盘侠',
    'version': (1, 0),
    'blender': (2, 90, 0),
}

import bpy
import os
import bpy.utils.previews
# 面板
#  呈现资产, 下拉框, ICON预览
#  呈现导入\保存 按钮

# 按钮
#   导入, 将选中的 模型资产 导入到场景
#   保存, 将我们选中的 模型(场景) 导出到 资产路径

# 属性
#   下拉框属性 Enum  动态生成
#   保存文件名 String
#   资产路径   String


class ImpOps(bpy.types.Operator):
    bl_idname = "ma.import"
    bl_label = "模型导入"
    bl_description = "将选定的模型资产 导入到场景"
    path: bpy.props.StringProperty(name="资产路径", default="")
    # bl_options = {"REGISTER", "UNDO"}

    def execute(self, context):
        path = self.path
        if not os.path.exists(path):
            self.report({"ERROR"}, f"资产{path}不存在")
            return {"FINISHED"}

        objects = []
        with bpy.data.libraries.load(path) as (df, dt):
            # dt --- data_to    场景数据(bpy.data)
            # df --- data_from  blend文件数据
            # 可导入信息类型--可以参考blend程序中的数据api

            # 导入所有物体
            dt.objects = df.objects
            objects = df.objects

        for ob in objects:
            bpy.context.scene.collection.objects.link(ob)
        return {"FINISHED"}


class ExpOps(bpy.types.Operator):
    bl_idname = "ma.export"
    bl_label = "模型保存"
    bl_description = "将选定的模型 保存到资产"
    path: bpy.props.StringProperty(name="资产路径", default="")
    # bl_options = {"REGISTER", "UNDO"}

    def execute(self, context):
        ob = context.object
        if not ob:
            self.report({"ERROR"}, "没有激活物体被选")
            return {"FINISHED"}
        if not self.path:
            self.path = ob.name
        path = os.path.join(os.path.dirname(__file__), "assets", self.path)

        if not path.endswith(".blend"):
            path += ".blend"

        saveDataBlocks = set(bpy.context.selected_objects)
        bpy.data.libraries.write(filepath=path, datablocks=saveDataBlocks)

        return {"FINISHED"}


class Panel(bpy.types.Panel):
    bl_label = "Model Asset Manager"
    bl_idname = 'MA_PT_Manager'
    bl_space_type = "VIEW_3D"
    bl_region_type = "UI"
    bl_category = "Model Manager"

    def draw(self, context):
        col = self.layout.column()
        col.prop(bpy.context.scene, "maassets")
        col.template_icon_view(bpy.context.scene, "maassets", show_labels=True,
                               scale_popup=7)
        opp = col.operator(ImpOps.bl_idname)
        opp.path = bpy.context.scene.maassets
        opp = col.operator(ExpOps.bl_idname)
        opp.path = bpy.context.scene.mapath
        col.prop(bpy.context.scene, "mapath")
        col.prop(bpy.context.scene, "madir")


clss = [ImpOps, ExpOps, Panel]
reg, unreg = bpy.utils.register_classes_factory(clss)


def register():
    reg()
    bpy.types.Scene.mapath = bpy.props.StringProperty(name="资产名")
    defaultPath = os.path.join(os.path.dirname(__file__), "assets")
    bpy.types.Scene.madir = bpy.props.StringProperty(default=defaultPath,
                                                     name="资产路径",
                                                     subtype="DIR_PATH")
    pathList = []
    prev = bpy.utils.previews.new()
    def getItems(self, context):
        pathListTemp = []
        defaultPath = bpy.context.scene.madir
        for file in os.listdir(defaultPath):
            if not file.endswith(".blend"):
                continue
            head, ext = os.path.splitext(file)
            pngPath = os.path.join(defaultPath, head + ".png")
            fullPath = os.path.join(defaultPath, file)
            # 加载 icon
            if file not in prev:
                prev.load(file, pngPath, "IMAGE", force_reload=True)
            pathListTemp.append((fullPath, file, "", prev[file].icon_id, len(pathListTemp)))
        if pathList != pathListTemp:
            pathList.clear()
            pathList.extend(pathListTemp)
        return pathList

    bpy.types.Scene.maassets = bpy.props.EnumProperty(items=getItems)


def unregister():
    unreg()
    del bpy.types.Scene.mapath
    del bpy.types.Scene.madir
    del bpy.types.Scene.maassets
